<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="canvas" width="800" height="800"></canvas>

  <script>
    const canvasDom = document.getElementById('canvas')
    const drawer = canvasDom.getContext('2d')

    // Path2D()可使用最新版本的浏览器中的对象来缓存或记录这些绘图命令，快速播放路径
    var rectangle = new Path2D()//构建对象
    rectangle.rect(100, 100, 50, 50)//构建正方形
    drawer.stroke(rectangle);

    const polyline = new Path2D('M10 10 h 80 v 80 h -80 z');

    // 线性渐变
    let index = 0
    const render = () => {
      drawer.clearRect(0, 0, canvasDom.clientWidth, canvasDom.clientHeight)
      index += 0.01
      if(index > 1) {index = 0}
      let linearGradient = drawer.createLinearGradient(0, 0, 600, 400)
      linearGradient.addColorStop(0, 'red')
      linearGradient.addColorStop(index, 'dodgerblue')
      linearGradient.addColorStop(1, 'green')
      drawer.fillStyle = linearGradient
      drawer.fill(polyline)
      drawer.fillRect(100, 200, 300, 300)
      requestAnimationFrame(render);
    }
    requestAnimationFrame(render);

  </script>
</body>

</html>